package org.jash.shop2201.shop

import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.google.android.material.search.SearchView
import com.youth.banner.Banner
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import dagger.hilt.android.AndroidEntryPoint
import org.jash.shop2201.BR
import org.jash.shop2201.R
import org.jash.shop2201.databinding.FragmentHomeBinding
import org.jash.shop2201.databinding.ItemHistoryBinding
import org.jash.shop2201.entity.BannerEntity
import org.jash.shop2201.entity.Goods
import org.jash.shop2201.mvvm.BaseFragment
import org.jash.shop2201.utils.CommonAdapter
import org.jash.shop2201.utils.StoreUtils


@Route(path = "/shop/home")
@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {
    val adapter by lazy { CommonAdapter<Goods>({R.layout.item_goods to BR.goods}) }
    val searchAdapter by lazy { CommonAdapter<Goods>({R.layout.item_goods to BR.goods}) }
    lateinit var keyword:String
    var page = 1
    val size = 10
    override fun initData() {
        viewModel.goodsLiveData.observe(viewLifecycleOwner) {
            if (page == 1) {
                adapter.clear()
            }
            adapter += it
            binding.refresh.closeHeaderOrFooter()
        }
        viewModel.searchLiveData.observe(viewLifecycleOwner) {
            searchAdapter.clear()
            searchAdapter += it
            if (it.isNotEmpty()) {
                StoreUtils.save("keywords", StoreUtils.getStringSet("keywords", setOf()) + keyword)
            }
            binding.history.isVisible = it.isEmpty()
        }
        viewModel.bannerLiveData.observe(viewLifecycleOwner) {
            binding.banner.update(it.map(BannerEntity::imagePath), it.map(BannerEntity::desc))
        }
        viewModel.loadBanner()
        viewModel.loadGoods(0, page, size)
    }

    override fun error(throwable: Throwable) {
        super.error(throwable)
        binding.refresh.closeHeaderOrFooter()
    }
    override fun initView() {
        binding.banner.setImageLoader(object :ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                imageView?.let {
                    Glide.with(it)
                        .load(path)
                        .into(it)
                }
            }
        })
        binding.searchView.addTransitionListener { _, _, state ->
            if (state == SearchView.TransitionState.SHOWING) {
                binding.history.isVisible = true
                searchAdapter.clear()
                val keywords = StoreUtils.getStringSet("keywords", setOf())
                binding.history.removeAllViews()
                keywords.forEach {
                    val item:ItemHistoryBinding = DataBindingUtil.inflate(layoutInflater, R.layout.item_history, binding.history, true)
                    item.item.text = it
                    item.item.setOnClickListener { _ ->
                        keyword = it
                        viewModel.searchGoods(keyword)
                    }
                }

            }

        }
        binding.searchView.editText.setOnEditorActionListener { v, _, event ->
            if (event.action == KeyEvent.ACTION_UP) {
                keyword = v.text.toString()
                viewModel.searchGoods(keyword)
            }
            true
        }
        binding.refresh.setOnRefreshListener {
            page = 1
            viewModel.loadGoods(0, page, size)
        }
        binding.refresh.setOnLoadMoreListener {
            viewModel.loadGoods(0, ++page, size)
        }
        binding.banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE)
        binding.recycler.adapter = adapter
        binding.searchRv.adapter = searchAdapter
    }

}